package com.yw.atp.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

public class ImageUtil {
	private static final int BUFFER_SIZE = 16 * 1024;
	public static String saveFile(File file,String path,String fName){
		String fileName = UUID.randomUUID().toString()+fName;
		File dstFile = new File(path+"\\"+fileName);
		copy(file,dstFile);
		return "upload/"+fileName;
	}
	
	public static String saveFile(InputStream in,String path,String fName){
		String fileName = UUID.randomUUID().toString()+fName;
		File dstFile = new File(path+"\\"+fileName);
		copy(in,dstFile);
		return "/upload/"+fileName;
	}
	
	//以下省略getter和setter......  
    //自己封装的一个把源文件对象复制成目标文件对象  
    private static void copy(File src, File dst) {  
        InputStream in = null;  
        OutputStream out = null;  
        try {  
            in = new BufferedInputStream(new FileInputStream(src),BUFFER_SIZE);  
            out = new BufferedOutputStream(new FileOutputStream(dst),BUFFER_SIZE);  
            byte[] buffer = new byte[BUFFER_SIZE];  
            int len = 0;  
            while ((len = in.read(buffer)) > 0) {  
                out.write(buffer, 0, len);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (null != in) {  
                try {  
                    in.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
            if (null != out) {  
                try {  
                    out.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }
    
    private static void copy(InputStream in,File dst){  
        OutputStream out = null;  
        try {  
            in = new BufferedInputStream(in,BUFFER_SIZE);  
            out = new BufferedOutputStream(new FileOutputStream(dst),BUFFER_SIZE);  
            byte[] buffer = new byte[BUFFER_SIZE];  
            int len = 0;  
            while ((len = in.read(buffer)) > 0) {  
                out.write(buffer, 0, len);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (null != in) {  
                try {  
                    in.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
            if (null != out) {  
                try {  
                    out.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }
}
